package com.uphone.kingmall.activity.personal;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.AttendanceViewMap;
import com.uphone.kingmall.adapter.UserShopTypeAdapter;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.UserShopInfoBean;
import com.uphone.kingmall.bean.UserShopTypeBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CaptureFileUtils;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.FileUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.HttpParamsUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.PermissionsUtils;
import com.uphone.kingmall.utils.PhoneFormatCheckUtils;
import com.uphone.kingmall.utils.PopupUtil;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.view.SubmitButton;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail :
 *     time   : 2018/07/31
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class ShangJiaRuZhuActivity extends BaseActivity {
    private static final int MAX_PCITURE = 2;
    private static final int IMAGE_PICKER = 100;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.et_shop_des)
    EditText etShopDes;
    @BindView(R.id.et_shop_sort)
    TextView etShopSort;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_address)
    TextView etAddress;
    @BindView(R.id.et_codee)
    EditText etCodee;
    @BindView(R.id.et_register_name)
    EditText etRegisterName;
    @BindView(R.id.et_address_shop)
    EditText etAddressShop;
    @BindView(R.id.btn_commit)
    SubmitButton btnCommit;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    private UserShopInfoBean bean;
    private List<UserShopTypeBean.ShopCatsBean> shopCats;
    private UserShopInfoBean.ApplyInfoBean info;
    private int catId = -1;
    private String address = "";
    private String regionStr = "";
    private PopupUtil popupFilter;
    private int mItem = -1;
    private LatLng latlng;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_shangjiaruzhu;
    }

    @Override
    public void initView() {
        setStatusBar();
        btnCommit.setRelaViews(etShopName, etAddressShop, etShopDes, etShopSort, etRegisterName, etPhone, etAddress, etCodee, etUsername);
    }

    @Override
    public void initData() {
        loadData();
    }

    private void loadData() {
        OkGoUtils.normalRequest(MyUrl.getShopApplyInfo, null, new onNormalRequestListener() {


            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    bean = GsonUtils.getGson().fromJson(body, UserShopInfoBean.class);
                    if (bean != null) {
                        info = bean.getApplyInfo();
                        if (info != null) {
                            if (TextUtils.equals("1", info.getShopState())) {
                                //已通过
                                CommonUtil.startIntent(ShangJiaRuZhuActivity.this, ShangJiaRuZhuSuccessActivity.class);
                                finish();
                            }
                            if (TextUtils.equals("2", info.getShopState())) {
                                //审核中
                                btnCommit.setEnabled(false);
                                btnCommit.setRelative(false);
                                btnCommit.setText("审核中");
                                btnCommit.setBackgroundResource(R.drawable.bg_gray_round);
                            } else {
                                btnCommit.setText("提交");
                                btnCommit.setEnabled(true);
                                btnCommit.setRelative(true);
                                btnCommit.init();
                            }
                            etAddress.setText(info.getShopAddr() + "");
                            etCodee.setText(info.getShopRegNo() + "");
                            etPhone.setText(info.getShopPhone() + "");
                            etRegisterName.setText(info.getShopRegNm() + "");
                            etShopDes.setText(info.getShopDesc() + "");
                            etUsername.setText(info.getOwnerName() + "");
                            etShopName.setText(info.getShopName() + "");
                            String shopLonLat = info.getShopLonLat();
                            String[] split = shopLonLat.split(",");
                            if (split != null && split.length == 2) {
                                latlng = new LatLng(Double.parseDouble(split[1]), Double.parseDouble(split[0]));
                            }
                            regionStr = CommonUtil.getStr(info.getShopRegion());
                            address = CommonUtil.getStr(info.getShopAddr());
                            etAddressShop.setText(info.getBusinessAddress() == null ? "" : info.getBusinessAddress());
                            loadNormalImage(info.getShopRegImg());
                            if (!TextUtils.isEmpty(info.getCatId())) {
                                if (shopCats != null) {
                                    for (int i = 0; i < shopCats.size(); i++) {
                                        if (TextUtils.equals("" + shopCats.get(i).getId(), info.getCatId())) {
                                            etShopSort.setText(shopCats.get(i).getCatName());
                                            catId = shopCats.get(i).getId();
                                            break;
                                        }
                                    }

                                }
                            }

                        }
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });

        OkGoUtils.normalRequest(MyUrl.getShopCats, null, new onNormalRequestListener() {


            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    UserShopTypeBean bean = GsonUtils.getGson().fromJson(body, UserShopTypeBean.class);
                    shopCats = bean.getShopCats();
                    if (shopCats != null) {
                        if (info != null) {
                            for (int i = 0; i < shopCats.size(); i++) {
                                if (TextUtils.equals("" + shopCats.get(i).getId(), info.getCatId())) {
                                    etShopSort.setText(shopCats.get(i).getCatName());
                                    catId = shopCats.get(i).getId();
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (popupFilter != null) {
            popupFilter.release();
        }
    }

    public void loadNormalImage(Object path) {
        RequestOptions requestOptions = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.pinagjia_tupian)
                .error(R.mipmap.pinagjia_tupian);
        Glide.with(this).load(path).apply(requestOptions).into(ivIcon);
    }

    @OnClick({R.id.iv_back, R.id.iv_icon, R.id.btn_commit, R.id.et_shop_sort, R.id.et_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_icon:
                showDialog();
                break;
            case R.id.et_address:
                CommonUtil.startIntent(this, AttendanceViewMap.class);
                break;
            case R.id.et_shop_sort:
                showPopup();
                break;
            case R.id.btn_commit:
                btnCommit.setEnabled(false);
                if (TextUtils.isEmpty(etShopName.getText().toString().trim()) || TextUtils.isEmpty(etAddressShop.getText().toString().trim()) || TextUtils.isEmpty(etShopDes.getText().toString().trim())
                        || TextUtils.isEmpty(etShopSort.getText().toString().trim()) || TextUtils.isEmpty(etUsername.getText().toString().trim())
                        || TextUtils.isEmpty(etPhone.getText().toString().trim()) || TextUtils.isEmpty(etAddress.getText().toString().trim())
                        || TextUtils.isEmpty(etCodee.getText().toString().trim()) || TextUtils.isEmpty(etRegisterName.getText().toString().trim())) {
                    showShortToast("请将数据填写完整");
                    btnCommit.setEnabled(true);
                    return;
                }
                if (!PhoneFormatCheckUtils.isPhoneLegal(etPhone.getText().toString())) {
                    showShortToast("手机号不正确");
                    btnCommit.setEnabled(true);
                    return;
                }
                if (bean != null && bean.getApplyInfo() != null && bean.getApplyInfo().getShopRegImg() != null) {

                } else {
                    if (cropPhoto == null) {
                        showShortToast("请上传照片");
                        btnCommit.setEnabled(true);
                        return;
                    }
                }
                if (latlng == null) {
                    ToastUtils.showShortToast(this, "地点获取失败，请重新选择！");
                    btnCommit.setEnabled(true);
                    return;
                }
                HttpParams params = HttpParamsUtils.getInstance()
                        .put("businessAddress", etAddressShop.getText().toString().trim())
                        .put("shopName", etShopName.getText().toString().trim())
                        .put("shopDesc", etShopDes.getText().toString().trim())
                        .put("ownerName", etUsername.getText().toString().trim())
                        .put("provCd", 0)
                        .put("cityCd", 0)
                        .put("distCd", 0)
                        .put("shopLonLat", latlng.longitude + "," + latlng.latitude)
                        .put("catId", catId)
                        .put("shopPhone", etPhone.getText().toString().trim())
                        .put("shopRegion", regionStr)
                        .put("shopAddr", address)
                        .put("shopPhone", etPhone.getText().toString().trim())
                        .put("shopRegNo", etCodee.getText().toString().trim())
                        .put("shopRegNm", etRegisterName.getText().toString().trim())
                        .getParams();
                if (bean != null && bean.getApplyInfo() != null && bean.getApplyInfo().getShopId() != null) {
                    params.put("shopId", bean.getApplyInfo().getShopId());
                }
                if (tempFile != null) {
                    params.put("shopRegImg", tempFile, tempFile.getName());
                }

                OkGoUtils.progressRequest(MyUrl.applyShop, this, params, new onNormalRequestListener() {
                    @Override
                    public void onSuccess(String response, int code) {
                        btnCommit.setEnabled(true);
                        if (code == 0) {
                            KeyboardUtils.hideSoftInput(ShangJiaRuZhuActivity.this);
                            ToastUtils.showShortToast(ShangJiaRuZhuActivity.this, "提交成功!" + "");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ShangJiaRuZhuActivity.this.finish();
                                }
                            }, 500);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        btnCommit.setEnabled(true);
                    }
                });
                break;
        }
    }

    private void showPopup() {
        if (shopCats == null) {
            ToastUtils.showShortToast(this, "没有加载到店铺分类信息");
            return;
        }
        View inflate = View.inflate(this, R.layout.kingmall_popup_shop_type, null);
        RecyclerView rv = inflate.findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        final UserShopTypeAdapter userShopTypeAdapter = new UserShopTypeAdapter();
        rv.setAdapter(userShopTypeAdapter);
        userShopTypeAdapter.setNewData(shopCats);
        if (catId != -1) {
            userShopTypeAdapter.setSelectCatId(catId);
        }
        popupFilter = PopupUtil.getInstance(MyApplication.mContext, inflate);
        popupFilter.showBottom();
        inflate.findViewById(R.id.tv_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userShopTypeAdapter != null && userShopTypeAdapter.getSelectPosition() != -1) {
                    etShopSort.setText(shopCats.get(userShopTypeAdapter.getSelectPosition()).getCatName() + "");
                    catId = shopCats.get(userShopTypeAdapter.getSelectPosition()).getId();
                    popupFilter.dismiss();
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("请选择类别");
                }
            }
        });
        popupFilter.setDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (popupFilter != null) {
                    popupFilter.release();
                }
            }
        });

        userShopTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                userShopTypeAdapter.setSelectCatId(shopCats.get(position).getId());
            }
        });
    }


    private File tempFile;
    private File cropPhoto;
    private static final int PHOTO_REQUEST_CUT = 3;
    private static final int PHOTO_REQUEST_CAMERA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final String PHOTO_FILE_NAME1 = "temp_photo1.jpg";

    private void showDialog() {
        final CharSequence[] items = {"相册", "拍照"};
        AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int item) {
                        // 这里item是根据选择的方式，
                        mItem = item;
                        PermissionsUtils.getInstance().checkPermissions(ShangJiaRuZhuActivity.this, new PermissionsUtils.IPermissionsResult() {
                            @Override
                            public void passPermissions() {
                                paizhao(item);
                            }

                            @Override
                            public void refusePermissions() {

                            }
                        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                }).create();
        dlg.show();
    }

    private void paizhao(int item) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (item == 0) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,
                        PHOTO_REQUEST_GALLERY);
            } else {
                StartTakePhoto();
            }
        } else {
            if (item == 0) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,
                        PHOTO_REQUEST_GALLERY);
            } else {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    tempFile = new File(Environment
                            .getExternalStorageDirectory(),
                            PHOTO_FILE_NAME);
                    Uri uri = Uri.fromFile(tempFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent,
                            PHOTO_REQUEST_CAMERA);
                } else {
                    ToastUtils.showShortToast(ShangJiaRuZhuActivity.this, "未找到存储卡，无法存储照片！");
                }
            }

        }
    }

    void StartTakePhoto() {
        tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        CaptureFileUtils.startActionCapture(this, tempFile, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 10) {
            if (data != null) {
                latlng = data.getParcelableExtra("latlng");
                address = data.getStringExtra("address");
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String district = data.getStringExtra("district");
                regionStr = province + city + district;
                if (!TextUtils.isEmpty(address)) {
                    etAddress.setText(address);
                }
            }
        } else if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    crop(uri, 1);
                }
            } else {
                Log.e("radish", "图片NOT ");
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                if (tempFile != null && tempFile.exists()) {
                    LogUtils.e("tempFile.getPath()：" + tempFile.getPath());
                    crop(Uri.fromFile(tempFile), 0);
                }
            } else {
                Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                final byte[] bytes = InputStream2ByteArray(cropPhoto.getAbsolutePath());
                if (bytes != null && bytes.length > 0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadNormalImage(bytes);
                        }
                    }, 200);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


    private void crop(Uri uri, final int type) {

        if (type == 1) {
            tempFile = FileUtil.uriToFile(uri, this);
        }
        try {
            LogUtils.e("tempFile:" + tempFile.getAbsolutePath());
            final byte[] bytes = InputStream2ByteArray(tempFile.getAbsolutePath());
            if (bytes != null && bytes.length > 0) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNormalImage(bytes);
                    }
                }, 200);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            // 照相
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                paizhao(mItem);
            } else {
            }
        }
    }
}
